<template>
  <div class="page">
    <h2>危机事件与急性干预</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按工号/姓名/事件描述搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterType" placeholder="全部类型" style="width:180px">
        <el-option label="全部类型" :value="''" />
        <el-option v-for="t in types" :key="t" :label="t" :value="t" />
      </el-select>

      <el-select v-model="filterSeverity" placeholder="严重性" style="width:140px">
        <el-option label="全部" :value="''" />
        <el-option label="轻度" value="low" />
        <el-option label="中度" value="medium" />
        <el-option label="重度" value="high" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">上报事件</el-button>
        <el-button @click="exportCSV">导出事件</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="badge" label="工号" width="110" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="type" label="事件类型" width="160" />
      <el-table-column prop="severity" label="严重性" width="100">
        <template #default="{ row }">
          <el-tag :type="row.severity==='high'?'danger':row.severity==='medium'?'warning':'info'">{{ mapSeverity(row.severity) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="时间" width="160" />
      <el-table-column prop="intervention" label="干预记录" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="view(row.id)">查看</el-button>
          <el-button size="small" @click="openModal(row.id)" style="margin-left:8px">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑事件' : '上报事件'" v-model="showModal" width="720px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="工号/姓名">
          <el-input v-model="form.person" placeholder="F001 - 张三" />
        </el-form-item>
        <el-form-item label="事件类型">
          <el-select v-model="form.type" style="width:240px">
            <el-option v-for="t in types" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="严重性">
          <el-select v-model="form.severity" style="width:160px">
            <el-option label="轻度" value="low" />
            <el-option label="中度" value="medium" />
            <el-option label="重度" value="high" />
          </el-select>
        </el-form-item>
        <el-form-item label="事件描述">
          <el-input type="textarea" v-model="form.description" />
        </el-form-item>
        <el-form-item label="干预记录">
          <el-input type="textarea" v-model="form.intervention" placeholder="简要记录给予的急性干预/转诊建议" />
        </el-form-item>
        <el-form-item label="事件时间">
          <el-date-picker v-model="form.date" type="datetime" placeholder="选择时间" style="width:220px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_TYPES = ['作战相关创伤','非战斗创伤','自伤/自杀意念','急性精神障碍','其他'];
const DEFAULT_DATA = [
  { id:1, badge:'F001', name:'张强', person:'F001 - 张强', type:'作战相关创伤', severity:'high', description:'高强度救援后出现反复噩梦、回避', intervention:'现场情绪稳定、建议心理门诊随访', date:'2025-09-12 14:30' },
  { id:2, badge:'F002', name:'李静', person:'F002 - 李静', type:'自伤/自杀意念', severity:'high', description:'表达过自伤念头，已安全评估', intervention:'紧急转诊并安排随访', date:'2025-08-02 09:10' }
];

const data = ref([]);
const types = ref([]);
const q = ref('');
const filterType = ref('');
const filterSeverity = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ person:'', badge:'', name:'', type:'', severity:'low', description:'', intervention:'', date:'' });

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); types.value = JSON.parse(JSON.stringify(DEFAULT_TYPES)); }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.person.toLowerCase().includes(qq) || (d.description||'').toLowerCase().includes(qq))) return false;
    if(filterType.value && d.type !== filterType.value) return false;
    if(filterSeverity.value && d.severity !== filterSeverity.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else{ Object.assign(form,{person:'',badge:'',name:'',type:'',severity:'low',description:'',intervention:'',date:''}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.person || !form.type){ ElMessage.warning('工号/姓名与事件类型为必填项'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); } else{ const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({ id:nid }, JSON.parse(JSON.stringify(form)))); } showModal.value=false; ElMessage.success('保存成功'); }

function mapSeverity(s){ return s==='high'?'重度':s==='medium'?'中度':'轻度'; }

function view(id){ const it = data.value.find(x=>x.id===id); if(it){ ElMessage.info(`事件：${it.person} ${it.type} ${mapSeverity(it.severity)} ${it.date}`); } }

function deleteOne(id){ ElMessageBox.confirm('确认删除该事件记录？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function batchDelete(){ const ids = selectedIds.value.slice(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','person','type','severity','description','intervention','date'], ...data.value.map(d=>[d.id,d.person,d.type,d.severity,d.description||'',d.intervention||'',d.date||'']) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='firefighter_crisis.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>